<?php

use App\Models\Order;
use App\Models\Plan;
use App\Models\Referral;
use App\Models\User;
use Filament\Facades\Filament;
use Filament\Notifications\Notification;

function updateReferralCommission($plan_id, $order_id, $referral_id){
    $amount = Plan::find($plan_id)->price;
    $referral = User::find(Filament::auth()->user()->referred_by);
    if(!$referral_id){
        return;
    }
    $commission_rate = User::find($referral_id)->first()->commission_rate;
    $referral_commission = $amount * $commission_rate / 100;
    $original_referral_commission = User::find($referral_id)->first()->referral_commissions;
    $referral_commissions = $original_referral_commission + $referral_commission;
    User::find($referral_id)->update(['referral_commissions' => $referral_commissions]);
    Referral::where('user_id', Filament::auth()->id())->where('referred_by', $referral_id)->update(['referral_earning' => $referral_commission, 'order_id' => $order_id]);
    Notification::make('ReferralCommissionAdded')
        ->title('You have received referral commission from user ' . Order::where('order_id', $order_id)->first()->user->name)
        ->sendToDatabase(User::find($referral));
}

function updateOrderAfterPayment($order_id, $payment_id, $paid_at){
    Order::find($order_id)->update([
        'status' => 'completed',
        'paid_at' => $paid_at,
        'payment_id' => $payment_id,
    ]);
}

function generate_uuid() {
    return sprintf( '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
        // 32 bits for "time_low"
        mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ),

        // 16 bits for "time_mid"
        mt_rand( 0, 0xffff ),

        // 16 bits for "time_hi_and_version",
        // four most significant bits holds version number 4
        mt_rand( 0, 0x0fff ) | 0x4000,

        // 16 bits, 8 bits for "clk_seq_hi_res",
        // 8 bits for "clk_seq_low",
        // two most significant bits holds zero and one for variant DCE1.1
        mt_rand( 0, 0x3fff ) | 0x8000,

        // 48 bits for "node"
        mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff )
    );
}
